<?php

namespace app\api\controller;

use app\common\model\user\Openvpn;
use think\facade\Db;

class OpenvpnController extends BaseApiController
{
    public array $notNeedLogin = ['reg', 'userlog', 'sysinfo', 'sync', 'info', 'test'];

    public function reg()
    {
        $sn = input('sn');
        $ip = input('ip');
        if (strlen($sn) == 17) {
            $sn = strtoupper(str_replace(':', '', $sn));
        }
        if (strlen($sn) != 12 && strlen($sn) != 40) {
            die('sn err' . strlen($sn));
        }

        $client = Openvpn::where('sn', $sn);

        //处理遗留的vpn客户端
        if (substr($ip, 0, 9) == '10.20.10.') {
            $client = Openvpn::where('vpn_ip', $ip);
        } else {
            $client = Openvpn::where('sn', $sn);
        }

        $client = $client->find();

        if ($client) {
            $common_name = $client['common_name'];
            Openvpn::where('common_name', $common_name)->update(['sn' => $sn]);
//            echo file_get_contents('/etc/openvpn/client/' . $common_name . '.ovpn');
        } else {
            $files = scandir('/etc/openvpn/client/dist/');
            $file = $files[2];
            if (strpos($file, '.ovpn') !== false) {
                $common_name = str_replace('.ovpn', '', $file);
                $vpnip = str_replace('-', '.', substr($common_name, 6));
                $ifconfig = "ifconfig-push 10.20.$vpnip 255.255.255.0";
                //固化ip地址
                file_put_contents('/etc/openvpn/ccd/' . $common_name, $ifconfig);
                rename('/etc/openvpn/client/dist/' . $file, '/etc/openvpn/client/' . $file);
            }
            Openvpn::create([
                'sn' => $sn,
                'common_name' => $common_name,
                'create_time' => time(),
            ]);
        }
        echo file_get_contents('/etc/openvpn/client/' . $common_name . '.ovpn');

    }

    public function userlog()
    {
        //接收文件
        $file = request()->file('file');
        $data = input('data');
        $sn = input('sn');
        if ($file) {
            $path = app()->getRootPath() . "public/uploads/userlog/$sn/";
            $info = $file->move($path, time() . '.zip');
            return $this->success('上传成功');
        }
        return $this->fail('未知错误');
    }

    public function sysinfo()
    {
        $data = input('data');
        $sn = input('sn');
        if ($data) {
            $client = Openvpn::where('sn', $sn)->data(['sysinfo' => $data])->update();

        }
    }

    public function sync()
    {
        $rows = Openvpn::column('title,mac,sn,common_name,remark');
        foreach ($rows as $row) {
            if (strlen($row['sn']) == 40) {
                $sn = $row['sn'];
            } else {
                if ($row['mac']) {
                    $sn = $row['mac'];
                }
            }
            if ($sn) {
                $common_name = str_replace('.ovpn', '', $row['title']);
                $client = Openvpn::where('common_name', $common_name)->update([
                    'sn' => $sn,
                    'user_name' => $row['remark'],
                ]);
            }
        }

    }

    public function info()
    {

        try {
            $param = input('param');
            trace($param);
            $data = decrypt($param);
            trace($data);
            $data = json_decode($data, true);
            $sn = $data['sn'];
            $username = $data['username'];
            // 使用参数化查询防止 SQL 注入
            $client = Openvpn::where('sn', $sn)
                ->field('id, sn, ext_ip, vpn_ip, user_name')
                ->find();

            if ($client) {
                Openvpn::where('sn', $sn)->update(['user_name' => $username]);
                // 对敏感信息进行加密
                $encryptedData = [
                    'msg' => 'ok',
                    'id' => $client->id,
                    'sn' => $client->sn,
                    'ext_ip' => encrypt($client->ext_ip),
                    'vpn_ip' => encrypt($client->vpn_ip),
                    'user_name' => $client->user_name,
                ];
            } else {
                $encryptedData = [
                    'sn' => $sn,
                    'msg' => '未发现客户端ip,请联系管理员处理',
                    'ext_ip' => $_SERVER['REMOTE_ADDR'],
                ];
            }
            trace($encryptedData);
            echo json_encode($encryptedData, 256);
        } catch (\Exception $e) {
            // 记录异常日志
            \think\facade\Log::error($e->getMessage());
            echo json_encode(['msg' => $e->getMessage()], 256);
        }
    }

// 加密函数示例


    public function test()
    {
//        $data = ['sn'=>'DD0E8DDECEF35CB902279F83C5F7F9472DBD15EF','username'=>'开发部测试'];
//        $json = json_encode($data,256);
//        $encrypt = encrypt($json);
//        echo $encrypt;
//        echo '<br>';
//        echo decrypt($encrypt);
        $param = "4UwaDid1G8TvV603VitPsNzZP7V8UnjtbEVlWTbySmokHq8/+BJP+seytTPDxd+eVTn8T+SaTnwL9PR89nWBQWhYPlXYtc6EFs1V7/YuNpzW2wUNsW8nieyzT5gcJ7hK";
        $url = "http://vpn.portal.doctorcom.com/api/openvpn/info?param=" . urlencode($param);
        echo $url;
        echo '<br>';
        $contents = file_get_contents($url);
        echo $contents;
    }

}